package com.typhoon.spring_shiro.controller.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.typhoon.spring_shiro.constants.EntityError;
import com.typhoon.spring_shiro.constants.PermissionEntityError;
import com.typhoon.spring_shiro.constants.SessionConstant;
import com.typhoon.spring_shiro.utils.CommonUtils;
import com.typhoon.spring_shiro.utils.CookieUtils;
import com.typhoon.spring_shiro.utils.ResponseUtils;
import com.typhoon.spring_shiro.utils.encrypt.Encrypt;

/**
 * 拦截器抽象类
 * @author Typhoon
 * @date 2017-06-09 17:14
 * @since V2.0
 * @description 抽象一些工具方法
 */
public abstract class AbstractCustomInterceptor implements HandlerInterceptor {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCustomInterceptor.class);

	protected static final String STATUS_KEY = "code";

	protected static final String DATA_KEY = "data";

	protected static final String MSG_KEY = "msg";
	/**
	 * 组装返回参数
	 * 
	 * @author Typhoon
	 * @date 2017-06-05 20:21
	 * @since V2.0
	 * @param response
	 * @param entityError
	 */
	protected void putParamResult(HttpServletResponse response, EntityError entityError) {
		Map<String, Object> results = new HashMap<String, Object>();
		results.put(STATUS_KEY, entityError.getCode());
		results.put(MSG_KEY, entityError.getMsg());
		ResponseUtils.renderJson(response, JSONObject.toJSONString(results, SerializerFeature.WriteMapNullValue));
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}
	
	/**
	 * 根据sid解析workerId
	 * @author Typhoon
	 * @date 2017-06-09 16:49
	 * @since V2.0
	 * @param sid
	 * @return
	 */
	protected Long decryptWorkerId(HttpServletRequest request, HttpServletResponse response) {
		String sid = request.getParameter("sid");
		if (sid == null) {// 必要要有sid
			sid = CookieUtils.getCookie(request, SessionConstant.SESSION_KEY);
			if (sid == null) {
				this.putParamResult(response, PermissionEntityError.ILLEGA_ACCESS_ERROR);
				return null;
			}
		}
		String decodeSid = Encrypt.decrypt(sid);
		LOGGER.info("decodeSid=" + decodeSid);
		long workerId = CommonUtils.evalLong(decodeSid.substring(decodeSid.indexOf("|") + 1, decodeSid.lastIndexOf("|")));
		LOGGER.debug("当前登录workerId:{}", workerId);
		return workerId;
	}
}
